package main

import (
	"elegantGo/chapter08/pkg/validate"
	"elegantGo/chapter08/pkg/xss"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"net/http"
)

func main() {

	validate.RegisterValidation("xss", func(fl validator.FieldLevel) bool {
		err := xss.Validate(fl.Field().String())
		if err != nil {
			return false
		}
		return true
	})

	srv := gin.Default()
	srv.LoadHTMLGlob("chapter08/view/*.tmpl")

	srv.GET("/article/search", func(c *gin.Context) {
		type ArticleSearch struct {
			Keyword string `binding:"required"`
			//Keyword string `binding:"required,xss"`
		}

		request := new(ArticleSearch)
		if err := c.ShouldBind(request); err != nil {
			c.JSON(http.StatusOK, gin.H{"err": err.Error()})
			return
		}

		// 种两个用于演示的cookie
		c.SetCookie("token", "token123456", 86400*30, "/", "127.0.0.1", false, false)
		c.SetCookie("userID", "1", 86400*30, "/", "127.0.0.1", false, false)

		c.HTML(http.StatusOK, "search.tmpl", gin.H{
			//"keyword": template.HTML(request.Keyword), // 为了方便演示，template.HTML会显示原始字符串
			"keyword": request.Keyword, // 默认会自动对特殊符号转义
		})
	})

	srv.GET("/cookies", func(c *gin.Context) {
		fmt.Println(c.Request.URL.String())
	})

	srv.Run(":80")
}
